﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AttributeRouting;
using AttributeRouting.Web.Mvc;
using LuxDiner.Model.Orders;
using LuxDiner.Logic.Orders;
using LuxDiner.Logic.Financial;
using System.IO;
using Utils;
using System.Text;
namespace LuxDiner.Web.Management.Areas.Orders.Controllers
{
    [RouteArea("Orders")]
    [RoutePrefix("DealOrder")]
    public class DealOrderController : Controller
    {
        [Route("")]
        [Authorize(Roles = "Admin,DealOrderList")]
        public ActionResult Index()
        {
            return View();
        }

        [Route("NewOrder/{method:int}")]
        [Authorize(Roles="Admin,DealOrder")]
        public ActionResult NewOrder(int method)
        {
            ViewBag.Method = method;
            return View();
        }

        [Route("Order/{orderNo}")]
        public ActionResult Order(string orderNo)
        {
            DealOrderModel model = null;
            if (!string.IsNullOrEmpty(orderNo))
                model = DealOrderLogic.GetOrder(orderNo);
            return PartialView(model);
        }

        [Route("Print/{orderNo}")]
        public ActionResult Print(string orderNo)
        {
            DealOrderModel model = null;
            if (!string.IsNullOrEmpty(orderNo))
            {
                model = DealOrderLogic.GetOrder(orderNo);
                if (model != null)
                {
                    ViewBag.RemainPay = 0;
                    var lst = PaymentLogic.GetTopPayments(new Model.Financial.PaymentQuery()
                    {
                        CustomerID = model.CustomerID
                    });
                    if (lst != null && lst.Count > 0)
                    {
                        ViewBag.RemainPay = lst[0].Balance;
                    }

                    return View(model);
                }
            }
            throw new HttpException(404, "无法找到该单据");
        }

        //[Route("Export")]
        //public ActionResult Export()
        //{
        //    try
        //    {
        //        DealOrderQuery sea = new DealOrderQuery();
        //        sea.GetCustomer = true;
        //        sea.GetItems = true;
        //        sea.GetProduct = true;
        //        sea.GetCustomerCategory = true;
        //        sea.GetProductCategory = true;
        //        if (!string.IsNullOrEmpty(Request.Form.Get("customerID")))
        //            sea.CustomerID = int.Parse(Request.Form.Get("customerID"));
        //        sea.OrderNo = Request.Form.Get("orderNo");
        //        var orderStatus = Request.Form.Get("orderStatus");
        //        if (!string.IsNullOrEmpty(orderStatus))
        //            sea.OrderStatus = orderStatus.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
        //        var odb = Request.Form.Get("orderDateBefore");
        //        if (!string.IsNullOrEmpty(odb))
        //            sea.OrderDateBefore = DateTime.Parse(odb);
        //        var oda = Request.Form.Get("orderDateAfter");
        //        if (!string.IsNullOrEmpty(oda))
        //            sea.OrderDateAfter = DateTime.Parse(oda);
        //        var orderMethod = Request.Form.Get("orderMethod");
        //        if (!string.IsNullOrEmpty(orderMethod))
        //            sea.Method = orderMethod.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
        //        var lst = DealOrderLogic.GetOrders(sea);
        //        if (lst.Count > 0)
        //        {
        //            string txt = "单据号\t客户\t日期\t总金额\t单据类型\t产品\t单价\t数量\t单位\t备注\t配送地址\t客户分类\t产品分类";
        //            foreach (var o in lst)
        //            {
        //                foreach (var it in o.Items)
        //                {
        //                    txt += string.Format("\r\n{0}\t{1}\t{2:yyyy-MM-dd}\t{3:0.00}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\t{11}\t{12}", new object[] {
        //                    o.OrderNo,o.Customer.ComplexName,o.NoteDate,o.TotalMoney,Common.GetOrderName(o.Method),
        //                    it.Product.ProductName,it.UnitPrice.ToString().RemoveLastZero(2),it.Quantity.ToString().RemoveLastZero(),
        //                    it.Product.UnitName,it.AssistantQuantity,o.Delivers,
        //                    string.Join(",",o.Customer.Categories.Select(p=>p.CategoryName).ToArray()),
        //                    string.Join(",",it.Product.Categories.Select(p=>p.CategoryName).ToArray())
        //                    });
        //                }
        //            }
        //            var buffer = Encoding.UTF8.GetBytes(txt);
        //            return File(buffer, "application/octet-stream", "单据详表.txt");
        //        }
        //        else
        //            return Content("暂无数据");
        //    }
        //    catch (Exception ex)
        //    {
        //        Common.Logger.Error("", ex);
        //        return Content("服务器运行出错，请联系开发商。");
        //    }
        //}

        [Route("Export")]
        public ActionResult Export()
        {
            try
            {
                DealOrderQuery sea = new DealOrderQuery();
                sea.GetCustomer = true;
                sea.GetItems = true;
                sea.GetProduct = true;
                sea.GetCustomerCategory = true;
                sea.GetProductCategory = true;
                if (!string.IsNullOrEmpty(Request.Form.Get("customerID")))
                    sea.CustomerID = int.Parse(Request.Form.Get("customerID"));
                sea.OrderNo = Request.Form.Get("orderNo");
                var orderStatus = Request.Form.Get("orderStatus");
                if (!string.IsNullOrEmpty(orderStatus))
                    sea.OrderStatus = orderStatus.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                var odb = Request.Form.Get("orderDateBefore");
                if (!string.IsNullOrEmpty(odb))
                    sea.OrderDateBefore = DateTime.Parse(odb);
                var oda = Request.Form.Get("orderDateAfter");
                if (!string.IsNullOrEmpty(oda))
                    sea.OrderDateAfter = DateTime.Parse(oda);
                var orderMethod = Request.Form.Get("orderMethod");
                if (!string.IsNullOrEmpty(orderMethod))
                    sea.Method = orderMethod.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToArray();
                var lst = DealOrderLogic.GetOrderDetails(sea);
                if (lst.Count > 0)
                {
                    //var cusCategories = Logic.Members.CustomerCategoryLogic.GetCategories(null);
                    //var proCategories = Logic.Products.ProductCategoryLogic.GetCategories(null);
                    Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(Server.MapPath("/RootFiles/Templates/Exports/dealdetails.xls"));
                    var cells = workbook.Worksheets[0].Cells;
                    for (var i = 0; i < lst.Count; i++)
                    {
                        var item=lst[i];
                        cells[i + 1, 0].Value = item.OrderNo;
                        cells[i + 1, 1].Value = item.CustomerComplexName;
                        cells[i + 1, 2].Value = item.NoteDate.ToString("yyyy-MM-dd");
                        cells[i + 1, 3].Value = item.TotalMoney;
                        cells[i + 1, 4].Value = Common.GetOrderName(item.Method);
                        cells[i + 1, 5].Value = item.ProductName;
                        cells[i + 1, 6].Value = item.UnitPrice;
                        cells[i + 1, 7].Value = item.Quantity;
                        cells[i + 1, 8].Value = item.UnitName;
                        cells[i + 1, 9].Value = item.AssistantQuantity;
                        cells[i + 1, 10].Value = item.Money;
                        cells[i + 1, 11].Value = item.Delivers;
                        
                        //var customer = Logic.Members.CustomerLogic.GetModel(item.CustomerID);
                        //cells[i + 1, 12].Value = string.Join(",", customer.Categories.Select(p => p.CategoryName));
                        //var product = Logic.Products.ProductLogic.GetModel(item.ProductID);
                        //cells[i + 1, 13].Value = string.Join(",", product.Categories.Select(p => p.CategoryName));
                    }
                    var buffer = workbook.SaveToStream().ToArray();
                    return File(buffer, "application/octet-stream", "交易单据明细.xls");
                }
                else
                    return Content("暂无数据");
            }
            catch (Exception ex)
            {
                Common.Logger.Error("", ex);
                return Content("服务器运行出错，请联系开发商。");
            }
        }
    }
}
